<template>
  <div class="main">
    <div class="init" v-show="!onScan">
      <input
        placeholder="请输入地址  例如http://www.baidu.com/ "
        v-model="url"
      />
      <div class="botton" @click="start()">开始</div>
    </div>

    <div class="resust" v-if="onScan">
      <div class="top-title">
        <div class="title">{{ url }}</div>
        <div class="d-grid gap-2 d-md-block">
          <button class="btn btn-primary btn-sm" @click="report()">导出</button>
          <button class="btn btn-primary btn-sm" @click="clear()">清空</button>
          <button class="btn btn-secondary btn-sm" @click="stop()">退出</button>
        </div>
      </div>
      <div class="content">
        <div class="scan-url">
          <div class="pass">
            <div class="title-1" style="display: flex">
              <div style="flex: 1">已采集地址</div>
              <div class="form-check form-switch">
                <input
                  class="form-check-input"
                  type="checkbox"
                  role="switch"
                  id="flexSwitchCheckDefault"
                  v-model="qc"
                />
                <label class="form-check-label" for="flexSwitchCheckDefault"
                  >去重</label
                >
              </div>
            </div>
            <div class="list">
              <div
                class="item"
                :style="{ color: detailIndex === index ? '#69a6df' : '' }"
                v-for="(item, index) in list"
                style="word-break: break-all;"
                @click="showDetail(index)"
              >
                <div
                  style="padding: 2px 4px;background: #b6dcff;display: inline-block;border-radius: 2px;font-size: 12px;"
                >
                  {{ item.method }}
                </div>
                {{ item.url }}
              </div>
            </div>
          </div>
        </div>

        <div class="worr-detail">
          <div class="title-1">地址详情</div>
          <div class="text" contentEditable="true" v-html="detail"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
let ipcRenderer;
if (window.require) {
  ipcRenderer = window.require("electron").ipcRenderer;
}

let encoder = new TextEncoder();
export default {
  name: "",
  components: {},
  data() {
    return {
      onScan: false,
      history: [],
      url: "",
      detailIndex: -1,
      detail: "",
      urlSet: new Set(),
      list: [],
      showList: [],
      qc: true,
      webUrl: ""
    };
  },
  watch: {

  },
  created() {},
  mounted() {
    let h = window.sessionStorage.getItem("san-history");
    if (h) {
      this.history = JSON.parse(h);
    }
    //监听窗口变化
    if (ipcRenderer) {
      ipcRenderer.on("onBeforeSendHeaders", (event, data) => {
        let us = data.url.split("?");
        let url = us[0];
        let params = us.length > 1 ? us[1] : "";
        let last = url.substring(url.lastIndexOf("/"), url.length);
        if (data.resourceType !== "xhr" || last.indexOf(".") >= 0) {
          return;
        } else if (this.qc && this.urlSet.has(url)) {
          return;
        } else if (this.qc) {
          this.urlSet.add(url);
        }

        if (data.uploadData) {
          for (const key in data.uploadData) {
            if (data.uploadData[key].type === "rawData") {
              let ps = Array.from(data.uploadData[key].bytes)
                .map(function(item) {
                  return String.fromCharCode(item);
                })
                .join("");
              if (params) {
                params += "&" + ps;
              } else {
                params = ps;
              }
            }
          }
        }
        this.list.unshift({
          url: url,
          method: data.method,
          headers: data.requestHeaders,
          params: params
        });
      });

      ipcRenderer.on("scan-main-url-refresh-to", (event, data) => {
        this.webUrl = data;
      });
    }
  },
  methods: {
    clear() {
      this.list = [];
      this.detailIndex = -1;
      this.detail = "";
      this.urlSet.clear()
    },
    report() {
      let report =
        "caseSeq,apiSeq,apiName,url,api,function,purpose,parameter\n";
      let i = 0;
      for (let index = this.list.length - 1; index >= 0; index--, i++) {
        report += `c${i},${i},,${this.url},${this.list[index].url.replace(
          this.url,
          ""
        )},${this.list[index].method},,${this.list[index].params}\n`;
      }
      console.log(report);
      this.exportRaw("jmeterDataSet.csv", report);
    },
    exportRaw(name, data) {
      let urlObject = window.URL || window.webkitURL || window;
      let export_blob = new Blob([data]);
      let save_link = document.createElementNS(
        "http://www.w3.org/1999/xhtml",
        "a"
      );
      save_link.href = urlObject.createObjectURL(export_blob);
      save_link.download = name;
      this.fakeClick(save_link);
    },
    fakeClick(obj) {
      let ev = document.createEvent("MouseEvents");
      ev.initMouseEvent(
        "click",
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      );
      obj.dispatchEvent(ev);
    },
    showDetail(index) {
      this.detailIndex = index;
      let rsp = JSON.stringify(this.list[index], null, 4);
      let json = "";
      let arr = rsp.split("\n");
      for (let i in arr) {
        let item = arr[i].replace(/\s/g, "&nbsp;");
        json += "<div><font>" + item + "</font></div>";
      }
      this.detail = json;
    },
    stop() {
      this.onScan = false;
      this.webUrl = "";
      if (ipcRenderer) {
        ipcRenderer.send("close-scan-jmeter-window");
      }
    },
    toStart(data) {
      if (data.url) {
        this.url = data.url;
      }
    },
    start() {
      if (!this.url) {
        return;
      }
      if (this.url.indexOf("http") < 0) {
        this.url = "http://" + this.url;
      }
      if (this.url.lastIndexOf("/") == this.url.length - 1) {
        this.url = this.url.substring(0, this.url.length - 1);
      }

      this.onScan = true;

      if (ipcRenderer) {
        ipcRenderer.send("open-scan-jmeter-window", this.url);
      }
    }
  }
};
</script>

<style lang="less" scoped>
.main {
  user-select: text;
  box-sizing: border-box;
  padding: 10px;
  padding-top: 0;
  width: 100%;
  height: 100%;

  .init {
    width: 400px;
    margin: 0 auto;
    text-align: center;
    margin: 40px auto;

    input {
      border: 1px #bdc3c7 solid;
      border-radius: 4px;
      outline: none;
      width: 100%;
      padding: 4px 10px;
      box-sizing: border-box;
    }

    textarea {
      border: 1px #bdc3c7 solid;
      border-radius: 4px;
      outline: none;
      width: 100%;
      padding: 4px 10px;
      box-sizing: border-box;
      min-height: 3rem;
      resize: vertical;
      max-height: 10rem;
    }
  }

  .history {
    width: 100%;
    color: #7f8c8d;
    text-align: left;
    margin-top: 40px;

    .item {
      cursor: pointer;
      transition: all 0.2s linear;
      margin: 4px 0;
      border-radius: 4px;
      padding: 4px 10px;
    }

    .item:hover {
      background: #eeeeee;
    }
  }

  .botton {
    display: table;
    margin: 0px auto;
    padding: 4px 20px;
    border-radius: 4px;
    background: #3498db;
    color: #fff;
    cursor: pointer;
    margin-top: 40px;
  }

  .botton:hover {
    background: #2980b9;
  }

  .resust {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    .top-title {
      display: flex;
      box-sizing: border-box;
      padding: 10px;
      box-shadow: 0 0px 6px rgba(200, 200, 200, 0.1);
      background: #fff;
      border-radius: 6px;

      .title {
        line-height: 29px;
        color: #34495e;
        flex: 1;
        font-weight: bold;
      }

      .botton {
        margin: 0;
        margin-left: 10px;
      }
    }

    .top-title:hover {
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }

    .content {
      flex: 1;
      height: 100%;
      margin-top: 10px;
      overflow: hidden;
      box-sizing: border-box;
      display: flex;

      .scan-url {
        height: 100%;
        margin-right: 5px;
        flex: 1;
        box-sizing: border-box;
        padding: 10px;
        box-shadow: 0 0px 6px rgba(200, 200, 200, 0.1);
        background: #fff;
        border-radius: 6px;
        display: flex;
        flex-direction: column;

        .title-1 {
          margin-bottom: 10px;
          color: #34495e;
        }

        .pass {
          box-sizing: border-box;
          flex: 1;
          height: 10px;
          overflow: hidden;

          .item {
            font-size: 0.8rem;
            padding: 4px;
            color: #2f3e42;
            cursor: pointer;
          }

          .list {
            height: calc(100% - 40px);
            overflow: auto;
          }
        }
      }

      .worr-detail {
        width: 10px;
        height: 100%;
        margin-left: 5px;
        box-sizing: border-box;
        padding: 10px;
        box-shadow: 0 0px 6px rgba(200, 200, 200, 0.1);
        background: #fff;
        border-radius: 6px;
        flex: 1;
        display: flex;
        flex-direction: column;

        .text {
          overflow: auto;
          padding-top: 10px;
          color: #7f8c8d;
          flex: 1;
          width: 100%;
          height: 100%;
          resize: none;
          border: none;
          outline: none;
        }
      }

      .worr-detail:hover,
      .scan-url:hover {
        box-shadow: 0 0 6px rgba(0, 0, 0, 0.1);
      }
    }
  }
}
</style>